# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: leon

import json
from concurrent.futures import ThreadPoolExecutor
import requests


class UniswapAsyncFeedClient(object):
  def __init__(self, uniswap_mgr, logger, max_connections=20):
    super().__init__()
    self._uniswap_mgr = uniswap_mgr
    self._logger = logger
    self._executor = ThreadPoolExecutor(max_workers=max_connections)

  def _query_expect_bbo(self, symbol):
    try:
      bid0: list = self._uniswap_mgr.get_as_bid0(symbol)
      ask0: list = self._uniswap_mgr.get_as_ask0(symbol)
      return json.dumps({
          "symbol": symbol,
          "bid0": bid0,
          "ask0": ask0,
      })
    except requests.exceptions.RequestException as e:
      self._logger.error(f'RequestException: {e}')
      return None
    except AssertionError:
      return None

  def async_query_expect_bbo(self, symbol):
    if self._executor:
      fut = self._executor.submit(self._query_expect_bbo, symbol)
      return fut
    return None

  def _query_trades(self, symbol):
    try:
      trades: list = self._uniswap_mgr.get_trades(symbol)
      if not trades:
        return {}
      return json.dumps({
          "symbol": symbol,
          "trades": trades,
      })
    except requests.exceptions.RequestException as e:
      self._logger.error(f'RequestException: {e}')
      return None
    except AssertionError:
      return None

  def async_query_trades(self, symbol):
    if self._executor:
      fut = self._executor.submit(self._query_trades, symbol)
      return fut
    return None

  def stop(self):
    if self._executor:
      self._executor.shutdown(False)
    else:
      self._logger.warning('Already stopped')
    self._executor = None
